package ppjava12v1.chess.dao.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import ppjava12v1.chess.dao.GameDAO;
import ppjava12v1.chess.entities.games.Game;
import ppjava12v1.chess.entities.games.Move;
import ppjava12v1.chess.enums.Side;

import javax.annotation.Resource;

/**
 * Created by Reyst on 21.09.2014.
 */
@Repository
public class HibernateGameDAO implements GameDAO {

    @Resource(name = "sessionFactory")
    SessionFactory factory;

    private Session getSession(){
        Session session = null;
        try {
            session = factory.getCurrentSession();
        } catch (HibernateException ex) {
            session = factory.openSession();
        }

        if (session == null)
            session = factory.openSession();

        return session;
    }

    @Override
    public Game getGameById(long id) {
        Session s = getSession();
        return (Game)s.get(Game.class, id);
    }

    @Override
    public void saveGame(Game game) {
        Session s = getSession();
        s.saveOrUpdate(game);
    }

    @Override
    public Move getMove(Game game, int moveNumber, Side side) {

        Session s = getSession();

        Move move = (Move) s.createQuery("From Move where game = :game " +
                "and moveNumber = :moveNumber and side = :side")
                .setParameter("game", game)
                .setParameter("moveNumber", moveNumber)
                .setParameter("side", side)
                .uniqueResult();

        return move;
    }

    @Override
    public void saveMove(Move move) {
        Session s = getSession();
//        move.updateGameId();
        s.saveOrUpdate(move);
    }

}
